package com.example.admin.util;

import com.example.admin.util.inner.RSAKeyLoader;

import java.security.PrivateKey;
import java.security.PublicKey;
import javax.crypto.Cipher;
import java.util.Base64;
/**
 *
 *
 * <a href="https://opendocs.alipay.com/common/02fwvj?pathHash=dcd525e3">支付宝开放平台文档</a>
 *
 * <a href="https://help.aliyun.com/document_detail/64281.html">密钥生成参考文档</a>
 *
 */
public class RsaUtil {


    public static void main(String[] args) {
        try {
            // 加载公钥和私钥
            PublicKey publicKey = RSAKeyLoader.loadPublicKeyFromPem("D:/tools/gen_key/public_key.pem");
            PrivateKey privateKey = RSAKeyLoader.loadPrivateKeyFromPem("D:/tools/gen_key/private_key.pem");

            // 待加密的字符串
            String originalText = "123456";

            // 使用公钥加密
            byte[] encryptedData = encryptWithPublicKey(publicKey, originalText);

            // 使用私钥解密
            String decryptedText = decryptWithPrivateKey(privateKey, encryptedData);

            System.out.println("Original Text: " + originalText);
            System.out.println("Encrypted Data: " + Base64.getEncoder().encodeToString(encryptedData));
            System.out.println("Decrypted Text: " + decryptedText);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }




    /**
     * 使用公钥加密数据
     * @param publicKey 公钥
     * @param text 待加密的字符串
     * @return byte[] 加密后的数据
     * @throws Exception 如果加密失败
     */
    public static byte[] encryptWithPublicKey(PublicKey publicKey, String text) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(text.getBytes());
    }

    /**
     * 使用私钥解密数据
     * @param privateKey 私钥
     * @param data 待解密的数据
     * @return String 解密后的字符串
     * @throws Exception 如果解密失败
     */
    public static String decryptWithPrivateKey(PrivateKey privateKey, byte[] data) throws Exception {
        Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        byte[] decryptedData = cipher.doFinal(data);
        return new String(decryptedData);
    }
}
